#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
int main()
{
    int fd[2] = {0};
    int ret = pipe(fd);
    if (ret == -1)
    {
        printf("pipe error!\n");
    }
    pid_t id = fork();
    if (id > 0)
    {
        // 父进程读
        close(fd[1]);
        while (1)
        {
            char read_buf[1024];
            int ret = read(fd[0], read_buf, sizeof(read_buf));
            if (ret > 0)
            {
                read_buf[ret] = '0';
                printf("child say: %s", read_buf);
            }
            else if (ret == -1)
            {
                // 写端退出：
                break;
            }
            else
            {
                printf("read error!\n");
            }
        }
        //退出前记得回收子进程
        waitpid(id,NULL,0);
    }
    else if (id == 0)
    {
        // 子进程写
        close(fd[0]);

        int cnt=5;
        while (cnt)
        {
            char buffer[1024];
            read(0, buffer, sizeof(buffer));
            int ret = write(fd[1], buffer, sizeof(buffer));
            cnt--;
        }
        exit(1);
    }
    else
    {
        // 子进程创建失败：
        printf("fork error!\n");
    }
    return 0;
}